package com.li.sssp.pc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

@Controller
@RequestMapping("/pc")
public class handler {
	  
	@RequestMapping(value="index")
	public String Index(){
		return "pc/index";
	}
	
    
	
	
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String Upload(@RequestParam(value = "InputFile", required = false) CommonsMultipartFile file,
			HttpServletRequest request) throws IOException, BiffException, RowsExceededException, WriteException {
		String _path = null;
		if (!file.isEmpty()) {

			File directory = new File("");// 设定为当前文件夹 
			_path = directory.getAbsolutePath() + "/update/" + file.getOriginalFilename();
			System.out.println("上传的文件的名字是：" + _path);
			try {
				FileOutputStream os = new FileOutputStream(_path);
				InputStream in = file.getInputStream();
				int b = 0;
				while ((b = in.read()) != -1) {
					os.write(b);
				}
				os.flush();
				os.close();
				in.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			if (_path != null) {
				CheckforUrl(_path);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		// OperateExcel.writeExcel();
		return "redirect:index";
	}
	
	
	public void CheckforUrl(String filePath) throws BiffException, IOException, RowsExceededException, WriteException {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//
		System.out.println(dateFormat.format(new Date()));
		// row计数
		int i_gw = 0;
		int i_fgw = 0;
		int i_ys=0;

		// 装载file
		File file = new File(filePath);
		Workbook book = Workbook.getWorkbook(file);
		Sheet sheet0 = book.getSheet(0);
		// 根据book创建一个操作对象
		WritableWorkbook wbook = Workbook.createWorkbook(file, book);
		// 得到一个工作对象官网
		WritableSheet sh_gw = wbook.createSheet("官网", 1);
		Label label_gw_title0=new Label(0,0,"公司名称");
		Label label_gw_title1=new Label(1,0,"官网");
		sh_gw.addCell(label_gw_title0);
		sh_gw.addCell(label_gw_title1);
		
		// 得到一个工作对象 非官网
		WritableSheet sh_fgw = wbook.createSheet("商业网站", 2);
		
		//	得到疑似sheet
		WritableSheet sh_ys = wbook.createSheet("疑似", 3);
		Label label_ys_title0=new Label(0,0,"公司名称");
		Label label_ys_title1=new Label(1,0,"官网");
		Label label_ys_title3=new Label(2,0,"URL");
		sh_ys.addCell(label_ys_title0);
		sh_ys.addCell(label_ys_title1);
		sh_ys.addCell(label_ys_title3);
		// 循环读出需要check的值
		for (Cell cell : sheet0.getColumn(0)) {
			List<String> names=CheckUrl(cell.getContents());
			String _companyName = names.get(0);
			String _websiteName=names.get(1);
			String str_title=getTitle(cell.getContents());
			if (_companyName.equals(_websiteName)) {
				
				//	获取title
				
				if(str_title.contains(_websiteName)){	//	如果titel包含站点名称就是官网
					// 官网
					i_gw++;
					Label label_gw_name = new Label(0, i_gw, _websiteName);
					Label label_gw_url = new Label(1,i_gw, cell.getContents());
					sh_gw.addCell(label_gw_name);
					sh_gw.addCell(label_gw_url);
					
					System.out.println("官网：" + label_gw_name.getContents() + "Url:" + label_gw_url.getContents());
				
				}else{ //	疑似
					i_ys++;
					Label label_ys_name = new Label(0, i_ys, _websiteName);
					Label label_ys_title = new Label(1, i_ys, str_title);
					Label label_ys_url = new Label(2,i_ys, cell.getContents());
					sh_ys.addCell(label_ys_name);
					sh_ys.addCell(label_ys_title);
					sh_ys.addCell(label_ys_url);
					System.out.println("疑似：" + label_ys_name.getContents() + "title:" + label_ys_title.getContents());
				}
				
				
				
			} else {
				// 商业网站
				i_fgw++;
				Label label_fgw_url = new Label(2,i_fgw, cell.getContents());
				Label label_fgw_websiteName=new Label(1,i_fgw,str_title);
				Label label_fgw_companyName=new Label(0,i_fgw,_companyName);
				sh_fgw.addCell(label_fgw_url);
				sh_fgw.addCell(label_fgw_companyName);
				sh_fgw.addCell(label_fgw_websiteName);
				System.out.println("商业网站" + cell.getContents());
			}
			// System.out.println(cell.getContents());
			
		}
		wbook.write();
		wbook.close();
		book.close();
		System.out.println(dateFormat.format(new Date()));

	}
	
	
	/**
	 * 返回站点名称
	 * @param strUrl
	 * @return
	 * @throws IOException
	 */
	public  List<String> CheckUrl(String strUrl) throws IOException {

		// 1 getURL返回
		List<String> names = new ArrayList<>();
		names.add("0");
		names.add("2");
		String url = "http://icp.chinaz.com/" + strUrl;
		Document doc = Jsoup.connect(url).timeout(8000).get();

		Elements elements = doc.select("li[class=bg-gray clearfix]");
		if (elements.size() != 0) {

			String companyName = doc.select("li[class=bg-gray clearfix]").get(0).select("p").get(0).childNode(0)
					.outerHtml();
			String webName = doc.select("li[class=clearfix]").get(1).select("p").get(0).childNode(0).outerHtml();
			names.set(0, companyName);
			//name[0]=companyName;
			names.set(1,webName);
			
//			if (companyName.equals(webName)) {
//				name = companyName;
//			}
		}
		// Element element = doc.select("tbody[class=bg-gray clearfix]").get(0);
		// System.out.print(element);
		return names;
	}
	/**
	 * 返回站点title
	 * @param strUrl
	 * @return
	 * @throws IOException
	 */
	public String getTitle(String strUrl) throws IOException{
		String title=null;
		String url = strUrl;
		try {
			Document doc = Jsoup.connect("http://"+url).userAgent("Mozilla/5.0").timeout(5000).get();
			Elements elements = doc.select("title");
			if (elements.size() != 0) {

			title=	elements.get(0).text();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		

		
		
		return title;
	}
	
	

}
